<?php
/**
 * 
 * OrderAction.class.php (订单管理)
 *
 * @package      	jgsat
 * @author          liuxun QQ:147613338 <admin@jgsat.cn>
 * @copyright     	Copyright (c) 2008-2011  (http://www.jgsat.com)
 * @license         http://www.jgsat.com/license.txt
 * @version        	jgsat企业网站管理系统 v2.1 2011-03-01 jgsat.cn $
 */
if(!defined("JGsat")) exit("Access Denied");
class OrderAction extends BaseAction
{

    function _initialize()
    {	
		parent::_initialize();
		$this->dao = M('Order');
		$this->assign('bcid',0);
		$user =  M('User')->find($this->_userid);
		$this->assign('vo',$user);
                
        $count1 = M('Order')->where("userid=".$this->_userid)->count();
        $count2 = M('Order')->where("userid=".$this->_userid." and status<>0 and pay_status<>0 and shipping_status<>0")->count();
        $count3 = M('Order')->where("userid=".$this->_userid." and status=0 and pay_status=0 and shipping_status=0")->count();
        $count4 = M('Order')->where("userid=".$this->_userid." and status=4")->count();
        $this->assign('count1',$count1);  
        $this->assign('count2',$count2);  
        $this->assign('count3',$count3);  
        $this->assign('count4',$count4);
        $messagecount = M("User_message")->where("touserid=".$this->_userid." or touserid=0")->count();
        $this->assign('messagecount',$messagecount);
        
        if($this->_groupid==7){
            $sjcount1 = M('Order')->where("sjuserid=".$this->_userid)->count();
            $sjcount2 = M('Order')->where("sjuserid=".$this->_userid." and status=2")->count();
            $sjcount3 = M('Order')->where("sjuserid=".$this->_userid." and status<2 and (pay_status=2 or pay_status=3) and (shipping_status=0 or shipping_status=3)")->count();
            $sjcount4 = M('Order')->where("sjuserid=".$this->_userid." and status=5")->count();
            $sjcount5 = M('Order')->where("sjuserid=".$this->_userid." and status<2 and pay_status=3 and shipping_status=3")->count();
            $this->assign('sjcount1',$sjcount1);  
            $this->assign('sjcount2',$sjcount2);  
            $this->assign('sjcount3',$sjcount3);  
            $this->assign('sjcount4',$sjcount4);
            $this->assign('sjcount5',$sjcount5);
        }
    }

    public function index()
    {
        if($_REQUEST['sn']){
            $sn = get_safe_replace($_REQUEST['sn']);
            unset($_REQUEST['sn']);
        }
        $where="userid=".$this->_userid;
        if($sn!=""){
            $where.=" and sn=".$sn;
        }
        $act = get_safe_replace($_REQUEST['act']);
        if($act==1){
            $where.=" and pay_status<2";
            $this->assign('menuWZ',16);
        }
        elseif($act==2){
            $where.=" and shipping_status=0";
            $this->assign('menuWZ',16);
        }
        elseif($act==3){
            $where.=" and shipping_status=1";
            $this->assign('menuWZ',16);
        }
        elseif($act==4){
            $where.=" and status=2";
            $this->assign('menuWZ',16);
        }
        elseif($act==5){
            $where.=" and status=5";
            $this->assign('menuWZ',16);
        }
        elseif($act==6){
            $where.=" and status<>0 and pay_status<>0 and shipping_status<>0";
            $this->assign('menuWZ',17);
        }
        elseif($act==7){
            $where.=" and status=0 and pay_status=0 and shipping_status=0";
            $this->assign('menuWZ',18);
        }
        elseif($act==8){
            $where.=" and status=4";
            $this->assign('menuWZ',19);
        }
        else{
            $this->assign('menuWZ',16);            
        }
        $count = $this->dao->where($where)->count();
        if($count){
            import ( "@.ORG.Page" );
            $listRows = 10;
            $page = new Page ( $count, $listRows );
            $pages = $page->show();
            $field =  $this->module[$this->mod[$module]]['listfields'];
            $field =  "*";
            $list = $this->dao->field($field)->where($where)->order("id desc")->limit($page->firstRow . ',' . $page->listRows)->select();
            foreach($list as $k=>$r){
                $prolist=M("Order_data")->where("order_id=".$r["id"])->select();
                $list[$k]["prolist"]=$prolist;
                $list[$k]["countpro"]=  count($prolist);
                
                if($r["pay_status"]<2 && $r['pay_code']!=""){
                    if($r['pay_code']=='Balance'){				
                        $paybutton='<input type="button" name="bpay" onclick="jgbuypay('.$r['id'].')" value="支付" class="blue_font" />';
                    }else{
                        $pay_code = $r['pay_code'];
                        $Payment = M('Payment')->find($r["pay_id"]);
                        $aliapy_config = unserialize($Payment['pay_config']);
                        $aliapy_config['order_sn']= $r['sn'];
                        $aliapy_config['order_amount']= $r['order_amount'];
                        $aliapy_config['body'] = $r['consignee'].' '.$r['postmessage'];
                        import("@.Pay.".$pay_code);
                        $pay=new $pay_code($aliapy_config);
                        $paybutton = $pay->get_code();
                        $this->assign('paybutton',$paybutton);
                    }
                    $this->assign('paybutton',$paybutton);
                }
                
                
            }
            $this->assign('pages',$pages);
            $this->assign('list',$list);
        }    
        $this->assign('act',$act);
        $this->display();
    }
    
    public function sjindex()
    {
        if($_REQUEST['sn']){
            $sn = get_safe_replace($_REQUEST['sn']);
            unset($_REQUEST['sn']);
        }
        $where="sjuserid=".$this->_userid;
        if($sn!=""){
            $where.=" and sn=".$sn;
        }
        $act = get_safe_replace($_REQUEST['act']);
        if($act==1){
            $where.=" and status=2";
            $this->assign('menuWZ',6);
        }
        elseif($act==2){
            $where.=" and shipping_status=1";
            $this->assign('menuWZ',5);
        }
        elseif($act==3){
            $where.=" and shipping_status=0";
            $this->assign('menuWZ',5);
        }
        elseif($act==4){
            $where.=" and status=5";
            $this->assign('menuWZ',8);
        }
        elseif($act==5){
            $where.=" and status=2";
            $this->assign('menuWZ',6);
        }
        elseif($act==6){
            $where.=" and status<2 and (pay_status=2 or pay_status=3) and (shipping_status=0 or shipping_status=3)";
            $this->assign('menuWZ',7);
        }
        elseif($act==7){
            $where.=" and status=5";
            $this->assign('menuWZ',8);
        }
        elseif($act==8){
            $where.=" and status<2 and pay_status=3 and shipping_status=3";
            $this->assign('menuWZ',9);
        }
        else{
            $this->assign('menuWZ',5);            
        }
        $count = $this->dao->where($where)->count();
        if($count){
            import ( "@.ORG.Page" );
            $listRows =  10;
            $page = new Page ( $count, $listRows );
            $pages = $page->show();
            $field =  $this->module[$this->mod[$module]]['listfields'];
            $field =  "*";
            $list = $this->dao->field($field)->where($where)->order("id desc")->limit($page->firstRow . ',' . $page->listRows)->select();
            foreach($list as $k=>$r){
                $prolist=M("Order_data")->where("order_id=".$r["id"])->select();
                $list[$k]["prolist"]=$prolist;
                $list[$k]["countpro"]=  count($prolist);                
            }
            $this->assign('pages',$pages);
            $this->assign('list',$list);
        }    
        $this->display();
    }
    public function show()
    {
		$sn = intval($_REQUEST['sn']);
		$id= intval($_REQUEST['id']);
		$order = $id ? $this->dao->find($id) : $this->dao->getBySn($sn) ;
		if(!$order && $order['userid']!=$this->_userid) $this->success (L('do_empty'));

		$order_data = M('Order_data')->where("order_id='{$order[id]}'")->select();
		$amount=0;
		foreach($order_data as $key=>$r){
			$amount = $amount+$r['price'];
		}
	 if($order["prosta"]!=""){
             $arr=  explode("|", $order["prosta"]);
            $arr1=explode(",", $arr[0]);
            $arr2=explode(",", $arr[1]);
            $pro=M("Product")->find($order["product_id"]);
            //输出规格参数
            $prostandard=jgProStandard($pro["p_standard"]);
            foreach($prostandard["setup"] as $k2=>$r2){
                if($k2==0){
                    $order["jgprosta"]=$r2["name"].":".$r2["val"][$arr2[$k2]];
                }
                else{
                    $order["jgprosta"].=",".$r2["name"].":".$r2["val"][$arr2[$k2]];
                }
            }
        }
        if($order["gift"]>0){
            $order["giftprice"]=$order["gift"]/$this->exchange;
        }

		$Payment = M('Payment')->find($order['pay_id']);
		$Shipping = M('Shipping')->find($shippingid);
		$Area = M('Area')->getField('id,name');
		$this->assign('Area',$Area);
		$this->assign('Payment',$Payment);
		$this->assign('Shipping',$Shipping);


		if($order['pay_code'] && $order['status']<2 && $order['pay_status']<2){
			
			$aliapy_config = unserialize($Payment['pay_config']);
			$aliapy_config['order_sn']= $order['sn'];
			$aliapy_config['order_amount']= $order['order_amount'];
			$aliapy_config['body'] = $order['consignee'].' '.$order['postmessage'];
			import("@.Pay.".$order['pay_code']);
			$pay=new $order['pay_code']($aliapy_config);
			$paybutton = $pay->get_code();
			$this->assign('paybutton',$paybutton);
		}
		$this->assign('order',$order);
		$this->assign('order_data',$order_data);
		$this->assign('amount',$amount); 
                $template =  'show';
                $this->assign('menuWZ',16);  
                if($this->_groupid==7){
                    $template =  'sjshow';
                    $this->assign('menuWZ',5);  
                }
		$this->display('Order:'.$template);
    }

    public function codeshow()
    {
        if($_POST['jgdosubmit']){
            $oid = intval($_REQUEST['orderid']);
            $price = intval($_REQUEST['price']);
            if($price<=0) $this->error("金额只能为正数。");
            
            $order =$this->dao->find($oid) ;
            if($order["order_amount"]<$price)  $this->error("输入的金额超过订单总额。");
            if($order["status"]==2)  $this->error("此订单已经结束,不允许兑换了。");
            $data=array();
            $data["status"]=2;
            $result =$this->dao->where("id=".$oid)->save($data) ;
            if(false !== $result) {
                $constr="订单号:".$order["sn"]."的订单兑换成功!";
                $r=addUserMessage("购物体验劵使用",$constr,$order["userid"],  $this->_userid,  $this->_username);
                $this->assign ( 'jumpUrl', U('Order/sjindex') );
                $this->success(L('do_success'));
            }else{
                $this->error(L('do_error'));
            }
            exit;
        }
        
		$sn = $_REQUEST['codestr'];
		$order =$this->dao->where("djqcode='".$sn."'")->find() ;
		$this->assign('order',$order);
                
                $this->assign('menuWZ',5);  
		$this->display();
    }


	function ajax(){
		
		$model= M('Order');
		$id=intval($_POST['id']);
		$order = $model->find($id);
		if($order['userid']!=$this->_userid)die(json_encode(array('msg'=>L('do_empty'))));
		$_POST = get_safe_replace($_POST);
		if($_GET['do']=='saveaddress'){
			$r = $model->save($_POST);
			die(json_encode(array('id'=>1)));
		}elseif($_GET['do'] =='order_status'){
			$_POST['status']=3;
			$_POST['confirm_time']=time();
			$r = $model->save($_POST);
			die(json_encode(array('id'=>1)));
		}elseif($_GET['do'] =='pay_status'){
			$_POST['pay_status']=3;
			$r = $model->save($_POST);
			die(json_encode(array('id'=>1)));
		}elseif($_GET['do'] =='shipping_status'){
			$_POST['shipping_status']=$_POST['num'];
			unset($_POST['num']);
			$_POST['accept_time']= $_POST['shipping_status']==2 ? time() : '';
			$r = $model->save($_POST);
			die(json_encode(array('id'=>1)));
		}
	}
    public function edit()
    {
        $id= intval($_REQUEST['id']);
        $order = $id ? $this->dao->find($id) : '';
        $do = $_REQUEST['do']; 
        $this->assign('do',$do);
        $this->assign('id',$id);

        if($order['shipping_status']>1 && $do!='status'){
            $this->assign('dialog','1');
            $this->assign ( 'waitSecond', 2);
            $this->assign ( 'jumpUrl',1);
            $this->error (L('order_shippinged_no_edit'));
        }

        if($_REQUEST['dosubmit']){

            switch($do) {
                case 'data':
                    $modle = M('Order_data');
                    if($_GET['delete']){
                        $data_id = intval($_GET['data_id']);
                        $modle->delete($data_id);
                    }else{
                        foreach($_POST['data_id'] as $key=>$r){
                            $data=array();
                            $data['id'] = $r;
                            $data['product_price'] = $_POST['product_price'][$key];
                            $data['number'] =  $_POST['number'][$key];
                            $data['price'] = $data['product_price']*$data['number'];
                            $modle->save($data); 
                        }
                    }
                    $_POST = order_count($order); 
                break;

                case 'money':
                    $order['discount'] = $_POST['discount'];
                    $_POST  = order_count($order);
                break;

                case 'payment':
                    $order['pay_id'] = $_POST['pay_id'];
                    $_POST  = order_count($order);
                break;

                case 'shipping':					
                    $order['shipping_id'] = $_POST['shipping_id'];
                    $order['insure'] =  $_POST['insure_'.$order['shipping_id']] ? 1 : 0;
                    $_POST  = order_count($order);
                break;

                case 'status':					
                    $order[$_POST['type']] = $_POST['value'];

                    if($_POST['type'] == 'status' && $_POST['value']==2){
                        $order['confirm_time'] =time();
                    }elseif($_POST['type'] == 'shipping_status' && $_POST['value']==1){
                        $order['shipping_time'] =time();
                    }elseif($_POST['type'] == 'pay_status' && $_POST['value']==2){
                        die(json_encode(array('msg'=>L('do_error'))));
                        //$order['pay_time'] =time();
                    }elseif($_POST['type'] == 'shipping_status' && $_POST['value']==2){
                        $order['accept_time']=time();
                    }

                    if (false!==$this->dao->save($order)) {
//                        if($_POST['type'] == 'pay_status' && $this->_groupid==7 && $this->_userid){
//                            //记录消费的积分
//                            $jgmoney=$this->reward/100*$order['order_amount']*$this->exchange;
//                            $r =M('User')->where("id =".$order['shareuserid'])->setInc('point',$jgmoney);
//                            addUserDetail("通过分享引导购买成功获取积分",3,  $jgmoney,$order['shareuserid'],"",1,$id,1);
//                            //记录消费的积分
//                            $jgmoney=$this->rewardbuy/100*$order['order_amount']*$this->exchange;
//                            $r =M('User')->where("id =".$order['userid'])->setInc('point',$jgmoney);
//                            addUserDetail("购买产品返积分",4,  $jgmoney,$order['userid'],"",1,$id,1);
//                        }
                        die(json_encode(array('msg'=>L('do_ok'))));
                    }else{
                        die(json_encode(array('msg'=>L('do_error'))));
                    }
                break;				
            }

            if (false === $this->dao->create ())  $this->error ( $this->dao->getError () ); 
            if (false!==$this->dao->save()) {
                $this->assign('dialog','1');
                $jumpUrl = U(MODULE_NAME.'/show?id='.$_REQUEST['id']);
                $this->assign ( 'jumpUrl', $jumpUrl);
                $this->success ("操作成功!");
            }else{
                $this->error ("操作失败!");
            }
            exit;
        }

        switch($do) {
            case 'address':
                $Area = M('Area')->getField('id,name');
                $this->assign('Area',$Area);
            break;

            case 'payment':
                $payment = M('Payment')->field('id,pay_code,pay_name,pay_fee,pay_fee_type,pay_desc,is_cod,is_online')->where("status=1")->select();
                $this->assign('payment',$payment);
            break;

            case 'data':
                $order_data = M('Order_data')->where("order_id='{$order[id]}'")->select();
                $this->assign('order_data',$order_data);
            break;
            case 'shipping':
                $shipping = M('Shipping')->where("status=1")->select();
                $this->assign('shipping',$shipping);
            break;
        }

        $this->assign('order',$order);
        $this->assign('jgorder',"1");
        $this->display();
    }

    function deleteall(){
        $name = MODULE_NAME;
        $model = M ( $name );
        $ids=$_POST['ids'];
        if($this->_groupid!=7){
            $this->error("非法操作!");
        }
        
        if(!empty($ids) && is_array($ids)){
                $id=implode(',',$ids);
                if(false!==$model->delete($id)){
                        $this->success("删除成功!");
                }else{
                        $this->error("批量删除失败!");
                }
        }else{
                $this->error("缺少参数!");
        }
    }
    Public function addorder(){
        $db=M("Order");
        $_POST['ip'] = get_client_ip();
        $incometime=strtotime(get_safe_replace($_POST['incometime']));
        $regulartime=get_safe_replace($_POST['regulartime']);
        if(!$db->create($_POST)) {
            $this->error($db->getError());
        }
       // print_r($regulartime);exit;
        $db->incometime=$incometime;
        $db->regulartime=$regulartime;
        $db->userid= $this->_userid;
        $db->order_amount=get_safe_replace($_POST['number']);
        $db->amount=get_safe_replace($_POST['number']);
        //计算收益
        $income=0;         
        if(get_safe_replace($_POST['ordertype']==1)){
            $income=$_POST['number']*$this->config['daysyl'];
        }elseif ($_POST['ordertype']==2) {
            if($regulartime==3){
                $income=$_POST['number']*0.07;
            }elseif($regulartime==6){
                 $income=$_POST['number']*0.09;
            }elseif ($regulartime==9) {
                $income=$_POST['number']*0.092;
            }elseif ($regulartime==12) {
                 $income=$_POST['number']*0.11;
            }            
        }
        $db->income=$income;
        $db->status=0;
        $db->pay_status=0;
        $db->add_time= time();
        $db->lang = LANG_ID;
        $result	=$db->add();     
        if($result) {
            $data['sn']=  toDate(time(),"Ymd").$result;
            $db->where("id=".$result)->save($data);
            $this->assign ( 'jumpUrl', U('User/Pay/orderpay?id='.$result) );
            $this->success("进入订单付款页面!");
        }else{
            $this->error("购买失败");
        }
    }
	Public function record(){
        $this->dao= M('Order');
        $where="userid=".$this->_userid." and status=1";
        if(isset($_REQUEST['month'])){
               $where .=  " and regulartime=".$_REQUEST['month'];
                 $this->assign('month',$_REQUEST['month']);
           } 
        $count = $this->dao->where($where)->count();
        if($count){
                import ( "@.ORG.Page" );
                $listRows = 10;      
                $page = new Page ( $count, $listRows );
                $page->urlrule = geturl($cat,'',$this->Urlrule);
                $pages = $page->show();
                $field =  "*";
                $list = $this->dao->field($field)->where($where)->order($orderstr)->limit($page->firstRow . ',' . $page->listRows)->select();
                $this->assign('pages',$pages);
                $this->assign('list',$list);
        }
       $this->assign('menuWZ',31);
       $this->display();
    }
    Public function rechargepay(){
            
        $db=M("Order");
        $_POST['ip'] = get_client_ip();
        $incometime=0;
        $regulartime=0;
        $db->incometime=$incometime;
        $db->regulartime=$regulartime;
        $db->userid= $this->_userid;
        $db->order_amount=get_safe_replace($_POST['money_f']);
        $db->amount=get_safe_replace($_POST['money_f']);
        
        $db->ordertype=3;
        $db->income=0;
        $db->status=0;
        $db->pay_status=0;
        $db->add_time= time();
        $db->lang = LANG_ID;
        $result	=$db->add();     
        if($result) {
            $data['sn']=  toDate(time(),"Ymd").$result;
            $db->where("id=".$result)->save($data);
            if($_POST['payfor']!=""){
                $Payment = M('Payment')->find($_POST['payfor']);
                $pay_code = $Payment['pay_code'];
                $aliapy_config = unserialize($Payment['pay_config']);
                $aliapy_config['order_sn']= $data['sn'];
                $aliapy_config['order_amount']= $_POST['money_f'];
                $aliapy_config['body'] = "充值";
                import("@.Pay.".$pay_code);
                $pay=new $pay_code($aliapy_config);
                $paybutton = $pay->get_code();
                 //print_r($paybutton);exit;
                 echo "<script language=\"javascript\">window.open('".$paybutton."');</script>";
                 exit;
            }
        }else{
            $this->error("失败");
        }
        
    }
    Public function failRecharge(){
         $this->display();
    }
    
}
?>